import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import "./Login.css";

export default function Login() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");
  const navigate = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");

    try {
      const response = await fetch("http://localhost:8080/api/users/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: username,
          password: password,
        }),
      });

      if (!response.ok) {
        throw new Error("登录失败: " + response.statusText);
      }

      // 尝试解析响应
      const contentType = response.headers.get("content-type");
      let data;

      if (contentType && contentType.includes("application/json")) {
        // 如果是JSON格式，则解析为JSON
        data = await response.json();
        console.log("登录成功 (JSON响应):", data);
        // 存储token或用户信息
        localStorage.setItem("token", data.token || "");
        // 统一使用userInfo键存储用户信息
        localStorage.setItem("userInfo", JSON.stringify(data.user || {}));
      } else {
        // 否则，以文本形式解析
        const text = await response.text();
        console.log("登录成功 (文本响应):", text);
        data = { message: text };
        // 统一使用userInfo键存储用户信息
        localStorage.setItem(
          "userInfo",
          JSON.stringify({ username: username })
        );
      }

      // 设置成功消息
      setSuccess(data.message || "登录成功！");

      // 1秒后跳转到首页
      setTimeout(() => {
        navigate("/");
      }, 1000);
    } catch (err) {
      setError(err.message);
      console.error("登录错误:", err);
    }
  };

  return (
    <div className="login-container">
      <div className="login-form">
        <h2>登录</h2>
        {error && <div className="error-message">{error}</div>}
        {success && <div className="success-message">{success}</div>}
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <label htmlFor="username">用户名</label>
            <input
              type="text"
              id="username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">密码</label>
            <input
              type="password"
              id="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
          </div>
          <button type="submit" className="login-button">
            登录
          </button>
        </form>
        <p className="register-link">
          还没有账号？<Link to="/register">立即注册</Link>
        </p>
      </div>
    </div>
  );
}
